package com.tpp.user.service.impl;

import com.alibaba.nacos.common.utils.MD5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tpp.comm.pojo.TpImage;
import com.tpp.comm.pojo.TpUser;
import com.tpp.comm.util.JwtUtil;
import com.tpp.comm.util.LoginException;
import com.tpp.user.feign.ImageFeign;
import com.tpp.user.mapper.UserMapper;
import com.tpp.user.service.UserService;
import com.tpp.user.vo.UserVo;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ImageFeign imageFeign;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @SneakyThrows
    @Override
    public UserVo login(String phone, String password) {
        LambdaQueryWrapper<TpUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TpUser::getPassword, MD5Utils.md5Hex(password.getBytes()));
        wrapper.eq(TpUser::getPhone,phone);
        TpUser tpUser = userMapper.selectOne(wrapper);
        if(tpUser==null){
            throw new LoginException("用户名或密码错误");
        }
        UserVo userVo = new UserVo();
        UserVo.LoginUser loginUser = new UserVo.LoginUser();
        BeanUtils.copyProperties(tpUser,loginUser);
        TpImage tpImage = imageFeign.findImage(tpUser.getId(),0,0);
        loginUser.setImgUrl(tpImage.getImgUrl());
        userVo.setLoginUser(loginUser);

        UserVo.TokenVo tokenVo = new UserVo.TokenVo();
        tokenVo.setToken(jwtUtil.createJwt(userVo.getLoginUser().getId()));
        tokenVo.setExpTime(jwtUtil.getExpTime());
        tokenVo.setGenTime(jwtUtil.getGenTime());
        userVo.setTokenVo(tokenVo);

        String tokenKey="tppd13:token:"+tpUser.getId();

        BoundValueOperations<String, String> ops = stringRedisTemplate.boundValueOps(tokenKey);
        ops.set(tokenVo.getToken(),jwtUtil.getExpTime()*2, TimeUnit.MINUTES);

        return userVo;
    }

    @Override
    public UserVo.TokenVo refreshToken(String token) {

        Integer id = Math.abs(jwtUtil.parseJwt(token));

        String tokenKey="tppd13:token:"+id;

        BoundValueOperations<String, String> ops = stringRedisTemplate.boundValueOps(tokenKey);
        String newToken = ops.get();
        UserVo.TokenVo tokenVo = new UserVo.TokenVo();
        tokenVo.setToken(newToken);
        tokenVo.setExpTime(jwtUtil.getExtpimeByToken(newToken));
        tokenVo.setGenTime(jwtUtil.getGenTimeByToken(newToken));
        return tokenVo;
    }
}
